import {Message} from "element-ui";

/**
 * 项目通用工具包
 */
// import Vue from 'vue'
// import CryptoJS from 'crypto-js'
var jingtong_Regobj = {
  emailReg:/[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
  mobileReg:/(^(13|14|15|16|17|18|19)\d{9})$/,
  phoneReg:/[0-9-()]{7,18}$/,
  numberReg:/^[0-9]*$/,
  Id18Reg:/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/,
  Id15Reg:/\d{17}[\d|x]|\d{15}/,
  signlessNumReg:/^[1-9]\d*$/,
  negativeNumReg:/-^[1-9]\d*$/,
  integerNumReg:/^-?[1-9]\d*$/,
  chineseReg:/^[\u4e00-\u9fa5]$/,
  postcodeReg:/[1-9]\d{5}(?!\d)/,
  linefreeReg:/\n\s*\r/,
  enAndNum: /^[A-Za-z]+\d{1,19}$/
}
export default {
  validFromat:{
    ismobile:function(str){
//验证是否为手机号码
      if(jingtong_Regobj.mobileReg.test(str)){
        return true;
      }else{
        return false;
      }
    },
    isNumber:function(str){
//验证是否为数字
      if(jingtong_Regobj.numberReg.test(str)){
        return true;
      }else{
        return false;
      }
    },
    isSignlessNum:function(str){
//验证是否为正整数
      if(jingtong_Regobj.signlessNumReg.test(str)){
        return true;
      }else{
        return false;
      }
    },
    isNegativeNum:function(str){
//验证是否为负整数
      if(jingtong_Regobj.negativeNumReg.test(str)){
        return true;
      }else{
        return false;
      }
    },
    isInteger:function(str){
//验证是否为整数
      if(jingtong_Regobj.integerNumReg.test(str)){
        return true;
      }else{
        return false;
      }
    },
    isPostCode:function(str){
//验证是否为邮编
      if(jingtong_Regobj.postcodeReg.test(str)){
        return true;
      }else{
        return false;
      }
    },
    isAllChinese:function(str){
//验证是否全部是汉字
      var result={
        str:'',
        length:0,
        faillstr:[]
      };
      for(var i = 0;i<str.length;i++){
        if(str[i].match(jingtong_Regobj.chineseReg)){
          result.str+=str[i];
          result.length++;
        }else{
          result.faillstr.push({str:str[i],index:i});
        }
      }
      return result;
    },
    isEmail:function(str){
//验证是否为邮箱
      if(jingtong_Regobj.postcodeReg.test(str)){
        return true;
      }else{
        return false;
      }
    },
    isLinefre:function(str){
//验证是否为空白行
      if(jingtong_Regobj.linefreeReg.test(str)){
        return true;
      }else{
        return false;
      }
    },
    isEnAndNum:function(str){
      if(jingtong_Regobj.enAndNum.test(str)){
        return true;
      }else{
        return false;
      }
    },
    isId18num:function(str){
//验证是否为18位身份证号码
      if(jingtong_Regobj.Id18Reg.test(str)){
        return true;
      }else{
        return false;
      }
    },
    isId15num:function(str){
//验证是否为18位身份证号码
      if(jingtong_Regobj.Id15Reg.test(str)){
        return true;
      }else{
        return false;
      }
    }
  },
  Arabia_To_SimplifiedChinese: function(Num) {
    //大小写转换
    for (var i = Num.length - 1; i >= 0; i--) {
      Num = Num.replace(",", "") //替换Num中的“,”
      Num = Num.replace(" ", "") //替换Num中的空格
    }
    if (isNaN(Num)) { //验证输入的字符是否为数字
      //alert("请检查小写金额是否正确");
      return;
    }
    //字符处理完毕后开始转换，采用前后两部分分别转换
    var part = String(Num).split(".");
    var newchar = "";
    //小数点前进行转化
    for (var i = part[0].length - 1; i >= 0; i--) {
      if (part[0].length > 10) {
        //alert("位数过大，无法计算");
        return "";
      } //若数量超过拾亿单位，提示
      var tmpnewchar = ""
      var perchar = part[0].charAt(i);
      switch (perchar) {
        case "0":
          tmpnewchar = "零" + tmpnewchar;
          break;
        case "1":
          tmpnewchar = "一" + tmpnewchar;
          break;
        case "2":
          tmpnewchar = "二" + tmpnewchar;
          break;
        case "3":
          tmpnewchar = "三" + tmpnewchar;
          break;
        case "4":
          tmpnewchar = "四" + tmpnewchar;
          break;
        case "5":
          tmpnewchar = "五" + tmpnewchar;
          break;
        case "6":
          tmpnewchar = "六" + tmpnewchar;
          break;
        case "7":
          tmpnewchar = "七" + tmpnewchar;
          break;
        case "8":
          tmpnewchar = "八" + tmpnewchar;
          break;
        case "9":
          tmpnewchar = "九" + tmpnewchar;
          break;
      }
      switch (part[0].length - i - 1) {
        case 0:
          tmpnewchar = tmpnewchar;
          break;
        case 1:
          if (perchar != 0) tmpnewchar = tmpnewchar + "十";
          break;
        case 2:
          if (perchar != 0) tmpnewchar = tmpnewchar + "百";
          break;
        case 3:
          if (perchar != 0) tmpnewchar = tmpnewchar + "千";
          break;
        case 4:
          tmpnewchar = tmpnewchar + "万";
          break;
        case 5:
          if (perchar != 0) tmpnewchar = tmpnewchar + "十";
          break;
        case 6:
          if (perchar != 0) tmpnewchar = tmpnewchar + "百";
          break;
        case 7:
          if (perchar != 0) tmpnewchar = tmpnewchar + "千";
          break;
        case 8:
          tmpnewchar = tmpnewchar + "亿";
          break;
        case 9:
          tmpnewchar = tmpnewchar + "十";
          break;
      }
      newchar = tmpnewchar + newchar;
    }
    //替换所有无用汉字，直到没有此类无用的数字为止
    while (newchar.search("零零") != -1 || newchar.search("零亿") != -1 || newchar.search("亿万") != -1 || newchar.search("零万") != -1) {
      newchar = newchar.replace("零亿", "亿");
      newchar = newchar.replace("亿万", "亿");
      newchar = newchar.replace("零万", "万");
      newchar = newchar.replace("零零", "零");
    }
    //替换以“一十”开头的，为“十”
    if (newchar.indexOf("一十") == 0) {
      newchar = newchar.substr(1);
    }
    //替换以“零”结尾的，为“”
    if (newchar.lastIndexOf("零") == newchar.length - 1) {
      newchar = newchar.substr(0, newchar.length - 1);
    }
    return newchar;
  },
  calc_bettwen_startime_endtime: {
    min: 60000, //分
    hou: 60000 * 60, //时
    d1: 60000 * 60 * 24, //天
    show_friendly: function(sj, currenttime) {
      //参数为时间戳
      var str;
      var t_long;
      if (currenttime != null) {
        t_long = new Date(currenttime); //当前日期对象
      } else {
        t_long = new Date();
      }
      var t = t_long.getTime(); //当前时间的毫秒值
      var sj_t = new Date(sj); //传入的时间对象
      t = t - sj; //当前时间的毫秒值与传入时间的毫秒值之差
      var result;
      if (t_long.getFullYear() == sj_t.getFullYear()) {
        //			在同一年
        if ((t_long.getMonth() + 1) == (sj_t.getMonth() + 1)) {
          //在同一个月
          if (t_long.getDate() == sj_t.getDate()) {
            //在同一天
            if (t <= this.min) {
              //60秒以内
              result = Math.floor(t / 60000 * 60);
              if (result == 60) {
                str = "1分钟前";
              } else if (result < 10) {
                str = "刚刚";
              } else {
                str = (result + "秒前");
              }
            } else if (t > this.min && t <= this.hou) {
              //一小时内
              result = Math.floor(t / this.hou * 60);
              if (result == 60) {
                str = "1小时前";
              } else {
                str = (result + "分钟前");
              }
            } else if (t > this.hou && t <= this.d1) {
              //1天内
              result = Math.floor(t / this.hou);
              if (result == 24) {
                str = "昨天";
              } else {
                str = (result + "小时前");
              }
            }
          } else {
            //不在同一天
            if (t_long.getDate() - sj_t.getDate() == 1) {
              str = "昨天";
            } else if (t_long.getDate() - sj_t.getDate() == 2) {
              str = "前天";
            } else {
              str = (sj_t.getMonth() + 1) + "月" + sj_t.getDate() + "日";
            }
          }
        } else {
          //不在同一个月
          //				但是 一个月尾  一个月初
          str = (sj_t.getMonth() + 1) + "月" + sj_t.getDate() + "日";
        }
      } else {
        //不在同一年
        str = sj_t.getFullYear() + "年" + (sj_t.getMonth() + 1) + "月" + sj_t.getDate() + "日";
      }
      return str;
    },
    days: function(starttime, endtime) {
      return parseInt(Math.abs(endtime - starttime) / (1000 * 60 * 60 * 24));
    }
  },
  formatDate: function(date, format) {
    var o = {
      "M+": date.getMonth() + 1, //月份
      "d+": date.getDate(), //日
      "h+": date.getHours(), //小时
      "m+": date.getMinutes(), //分
      "s+": date.getSeconds(), //秒
      "q+": Math.floor((date.getMonth() + 3) / 3), //季度
      "S": date.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(format)) {
      format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
      if (new RegExp("(" + k + ")").test(format)) {
        format = format.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
      }
    }
    return format;
  },
  md5: function(str) {
    return CryptoJS.MD5(str).toString();
  },
  base64decode: function(str) {
    return JSON.parse(CryptoJS.enc.Base64.parse(str).toString(CryptoJS.enc.Utf8));
  },
  base64encode: function(str) {
    return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(str));
  },
  determineSex:function(type){
    if(type==1){
      return "男";
    }else if(type==2){
      return "女";
    }else{
      return "保密";
    }
  },
  determineBetType:function(type){
    if(type==1){
      return "余额";
    }else if(type==2){
      return this.$store.getters.getValForKey("sysConfig").coinName;
    }else{
      return "无限制";
    }
  },
  filterParamsNull:function(params){
    var data = {};
    for(var k in params){
      if(params[k]!=""&&params[k]!=null){
        data[k] = params[k];
      }
    }
    return data;
  },
  generateParams:function(params){
    /**
     * 根据不为空的过滤条件生成查询参数
     * @type {{}}
     */
    var p = {};
    var arr = [];
    var orderBy = "";
    for(var k in params){
      if(k=="findParams"){
        for(var key in params[k]){
          if(params[k][key].type===2){//这个是时间筛选的条件
            for(var i = 0;i<params[k][key].filter.length;i++){
              if(params[k][key].filter[i].params.value!=""&&params[k][key].filter[i].params.value!==null&&params[k][key].filter[i].params.value!=="null"){
                arr.push(params[k][key].filter[i].params);
                this.setFindParams(params[k][key].filter[i]);
              }else{
                params[k][key].filter[i].state=0;
              }
            }
          }else{
            if(params[k][key].params.value!==""&&params[k][key].params.value!==null){
              arr.push(params[k][key].params);
              this.setFindParams(params[k][key]);
            }else{
              params[k][key].state=0;
            }
          }
          orderBy = this.setOrderByParams(params[k][key],orderBy);
        }
      }else{
        if(params[k]!==""){
          p[k] = params[k];
        }
      }
    }
    if(arr.length>0){
      p.findParams = arr;
    }
    if(orderBy!==""){
      orderBy = orderBy.substring(0,orderBy.length-1);
      p.orderBy = orderBy;
    }
    return p;
  },
  setFindParams(param){
    // console.log(param);
    param.state=1;
    for(var i=0;i<param.conditions.options.length;i++){
      if(param.type===3){
        if(param.params.value!==""&&param.params.value===param.conditions.options[i]["opt"]){
          param.alias =param.conditions.options[i]["alias"];
        }
      }else {
        if (param.params.condition === param.conditions.options[i]["opt"]) {
          param.alias = param.conditions.options[i]["alias"];
        }
      }
    }
  },
  setOrderByParams(param, orderBy) {
    //时间筛选
    if (param.orderBy.state === 1 && param.orderBy.value !== "") {
      if (param.type === 2) {
        //时间 排序
        if(param.params.prefix!=null){
          orderBy = orderBy + param.params.prefix + this.underlineUpperCase(param.params.column) + " " + param.orderBy.value + ",";
        }else{
          orderBy = orderBy + param.filter[0].params.prefix + this.underlineUpperCase(param.params.column) + " " + param.orderBy.value + ",";
        }
      } else {
        //其他字段 排序
        orderBy = orderBy + param.params.prefix + this.underlineUpperCase(param.params.column) + " " + param.orderBy.value + ",";
      }
    }
    return orderBy;
  },
  isNull:function(str){
    if(str==null||str==undefined){
      return true
    }else{
      return false
    }
  },
  isEmpty:function(str){
    if(str==null||str==undefined||str.length==0){
      return true
    }else{
      return false
    }
  },
  underlineLowerCase(str){
    return str.replace(/\B([A-Z])/g, '_$1').toLowerCase();
  },
  underlineUpperCase(str){
    return str.replace(/\B([A-Z])/g, '_$1').toUpperCase();
  },
  msgError(msg){
    Message.error({
      message:msg,
      duration: 2500
    })
    throw new Error(msg);
  },
  msgSuccess(msg){
    Message.success({
      message:msg,
      duration: 2500
    })
  },
  msgWaring(msg){
    Message.warning({
      message:msg,
      duration: 2500
    })
  },
  Money(number,flag) {
    return accounting.formatMoney(number, !flag?"￥":flag, 2);
  },
  getTimeByTimeZone(timeZone,datetimeSecondTime) {
    var timezone = 8; //目标时区时间，东八区
    var offset_GMT = new Date(datetimeSecondTime).getTimezoneOffset(); // 本地时间和格林威治的时间差，单位为分钟
    var nowDate = new Date(datetimeSecondTime).getTime(); // 本地时间距 1970 年 1 月 1 日午夜（GMT 时间）之间的毫秒数
    var targetDate = new Date(nowDate + offset_GMT * 60 * 1000 + timezone * 60 * 60 * 1000);
    console.log("东8区现在是：" + targetDate);
    return targetDate;
    //
    // var d = new Date(datetimeSecondTime);
    // var localTime = d.getTime(),
    //   localOffset = d.getTimezoneOffset() * 60000, //获得当地时间偏移的毫秒数,这里可能是负数
    //   utc = localTime + localOffset, //utc即GMT时间
    //   offset = timeZone, //时区，北京市+8  美国华盛顿为 -5
    //   localSecondTime = utc + (3600000 * offset);  //本地对应的毫秒数
    //   console.log(localOffset);
    //   return new Date(localSecondTime);
  },
  createQrCode(id,text,w,h){
    QRCode.toCanvas(text, {type:"png", errorCorrectionLevel: 'H',width:w==null?180:w,height:h==null?180:h }, function (err, canvas) {
      if (err) {
        throw err
      }else{
        var container = document.getElementById(id);
        container.appendChild(canvas);
      }
    })
  },
  sorts:{
    sortByKeyDesc(array,key){
      return array.sort(function(a,b){
        var x = a[key];
        var y = b[key];
        return((x<y)?-1:((x>y)?1:0));
      })
    },
    sortByKeyAsc(array,key){
      return array.sort(function(a,b){
        var x = a[key];
        var y = b[key];
        return((x<y)?1:((x>y)?-1:0));
      })
    },
    sortNumberDesc(a,b){
      return a-b;
    },
    sortNumberAsc(a,b){
      return b-a;
    }
  }
}
